using QFramework;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(GridLayoutGroup))]
public class DynamicGridWithConstraints : MonoBehaviour
{
    [Header("父容器")]
    public RectTransform contentParent;

    [Header("宽高比配置")]
    public Vector2 referenceCellSize = new Vector2(110, 110); // 初始参考尺寸
    [Range(0.1f, 1f)] public float spacingRatio = 0.1f;      // 间距占单元格的比例

    [Header("宽度限制")]
    public float minCellWidth = 50f;  // 最小宽度
    public float maxCellWidth = 110f; // 最大宽度

    private GridLayoutGroup gridLayout;
    private float aspectRatio;

    private void Awake()
    {
        gridLayout = GetComponent<GridLayoutGroup>();
        aspectRatio = referenceCellSize.x / referenceCellSize.y;
    }

    private void OnTransformChildrenChanged()
    {
        UpdateGridLayout();
    }

    private void UpdateGridLayout()
    {
        int childCount = transform.childCount;
        if (childCount == 0 || contentParent == null) return;

        Vector2 parentSize = new Vector2(
            contentParent.rect.width - gridLayout.padding.horizontal,
            contentParent.rect.height - gridLayout.padding.vertical
        );

        // 遍历可能的列数，找到最佳方案
        int bestColumns = 1;
        float maxCellArea = 0;

        for (int columns = 1; columns <= childCount; columns++)
        {
            int rows = Mathf.CeilToInt(childCount / (float)columns);
            Vector2 cellSize = CalculateCellSize(parentSize, columns, rows);

            // 强制应用宽度限制
            cellSize.x = Mathf.Clamp(cellSize.x, minCellWidth, maxCellWidth);
            cellSize.y = cellSize.x / aspectRatio;

            float cellArea = cellSize.x * cellSize.y;

            if (cellArea > maxCellArea)
            {
                maxCellArea = cellArea;
                bestColumns = columns;
            }
        }

        ApplyFinalLayout(parentSize, bestColumns);
    }

    private Vector2 CalculateCellSize(Vector2 parentSize, int columns, int rows)
    {
        // 计算理论单元格尺寸
        float spacingX = (columns - 1) * (maxCellWidth * spacingRatio);
        float spacingY = (rows - 1) * ((maxCellWidth / aspectRatio) * spacingRatio);

        float cellWidth = (parentSize.x - spacingX) / columns;
        float cellHeight = cellWidth / aspectRatio;

        // 检查高度是否超出父容器
        if (cellHeight * rows + spacingY > parentSize.y)
        {
            cellHeight = (parentSize.y - spacingY) / rows;
            cellWidth = cellHeight * aspectRatio;
        }

        return new Vector2(cellWidth, cellHeight);
    }

    private void ApplyFinalLayout(Vector2 parentSize, int columns)
    {
        int rows = Mathf.CeilToInt(transform.childCount / (float)columns);
        Vector2 cellSize = CalculateCellSize(parentSize, columns, rows);

        // 最终应用宽度限制
        cellSize.x = Mathf.Clamp(cellSize.x, minCellWidth, maxCellWidth);
        cellSize.y = cellSize.x / aspectRatio;

        //我需要动态调整全部子节点的大小
        foreach (Transform child in transform)
        {
            Transform transform = child.transform.GetChild(0);
            if (transform != null)
            {
                //scale
                transform.localScale = new Vector3(cellSize.x / 110f, cellSize.y / 110f, 1f);
            }
        }
        gridLayout.cellSize = cellSize;
        gridLayout.spacing = new Vector2(
            cellSize.x * spacingRatio,
            cellSize.y * spacingRatio
        );
    }
}